package com.mt.roll.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jiff
 * @date 2019/11/27
 * @since 1.0
 */
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "corsFilter")
public class CorsFilter implements Filter {
    private static final String ALLOWED_HEADERS = "Content-Type, authorization, credential, token, X-Requested-With";
    private static final String ALLOWED_METHODS = "*";
    private static final String ALLOWED_ORIGIN = "*";
    private static final String ALLOWED_EXPOSE = "*";
    private static final String MAX_AGE = "18000L";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = ((HttpServletRequest) request);
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS);
        httpServletResponse.setHeader("Access-Control-Max-Age", MAX_AGE);
        httpServletResponse.setHeader("Access-Control-Allow-Headers", ALLOWED_HEADERS);
        httpServletResponse.setHeader("Access-Control-Expose-Headers", ALLOWED_EXPOSE);

        if (httpRequest.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.name())) {
            return;
        }
        chain.doFilter(request, response);
    }


    @Override
    public void destroy() {

    }
}
